//
//  ReportingViewController.m
//  nonghubao
//
//  Created by 王 文彬 on 13-10-25.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "ReportingViewController.h"
#import "JSONRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "UIViewController+MJPopupViewController.h"

@interface ReportingViewController ()
{
    ReportingCategory _category;  //举报类型
    long              _xID;       //被举报的ID
    
    UILabel*    _titleLabel;
    
    NSMutableArray* _radioButtonsState;
    NSMutableArray* _radioButtons;
    
    UITextView* _contentTextView;
    UIButton*   _confirmButton;
    UIButton*   _cancelButton;
    
    NSString*   _contentTextViewHolder;  //记录_contentTextView应该显示的holder，多个方法调用，全局
}

@end

@implementation ReportingViewController

@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithCategory:(ReportingCategory)category withID:(long)xID
{
    self = [super init];
    if (self) {
        _category = category;
        _xID = xID;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.frame = CGRectMake(0, 0, 280, 300);
    self.view.backgroundColor = [UIColor colorWithRed:166/255.0 green:206/255.0 blue:35/255.0 alpha:1];
    self.view.layer.cornerRadius = 5;
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, self.view.frame.size.width - 10 - 10, 30)];
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = _SYS_FONT_009;
    _titleLabel.text = _category == ReportingCategoryPeople ? _L(@"vc_title_102") : _L(@"vc_title_103");
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_titleLabel];
    
    
    //产生8个按钮，及其对应的状态数组
    _radioButtonsState = [[NSMutableArray alloc] initWithObjects:@(1), @(0), @(0), @(0), @(0), @(0), @(0), @(0), nil];
    NSArray* radioButtonsTitle = [NSArray arrayWithObjects:_L(@"title_95"), _L(@"title_96"), _L(@"title_97"), _L(@"title_98"), _L(@"title_99"), _L(@"title_100"), _L(@"title_101"), _L(@"title_102"), nil];
    
    _radioButtons = [[NSMutableArray alloc] initWithCapacity:_radioButtonsState.count];
    for (int i = 0; i < _radioButtonsState.count; i++) {

        int x = (i % 2) == 0 ? 25 : 145;  //偶数列：基数列
        int y = 70 + (25 + 0) * (i / 2);   //从n开始偏移 + (组件高度 + 间隙高度) * (行数)

        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, 100, 25)];
        [button addTarget:self action:@selector(radioButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:radioButtonsTitle[i] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor clearColor];
        button.tag = 100 + i;
        
        //第一个用选中的图
        if (i == 0) {
            [button setImage:[UIImage imageNamed:@"com_icon_021@2x"] forState:UIControlStateNormal];
        }
        //其他的用未选中的图
        else {
            [button setImage:[UIImage imageNamed:@"com_icon_020@2x"] forState:UIControlStateNormal];
        }

        [button setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, button.frame.size.width - 25 + 5 /*5=图片上下左右都缩小的距离，25=图片本身宽度*/)];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        [self.view addSubview:button];
        [_radioButtons addObject:button];
    }
    
    
    _contentTextViewHolder = _L(@"holder_48");
    
    _contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height - 120, self.view.frame.size.width - 10 - 10, 60)];
    _contentTextView.delegate = (id)self;
    _contentTextView.layer.cornerRadius = 5;
    _contentTextView.text = _contentTextViewHolder;
    _contentTextView.font = _SYS_FONT_003;
    _contentTextView.textColor = _SYS_COLOR_003;
    _contentTextView.returnKeyType = UIReturnKeyDone;
    [self.view addSubview:_contentTextView];
    
    
    _confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(20, self.view.frame.size.height - 50, 110, 35)];
    [_confirmButton setBackgroundImage:[UIImage imageNamed:@"com_btn_040_n"] forState:UIControlStateNormal];
    [_confirmButton addTarget:self action:@selector(confirmButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_confirmButton setTitle:_L(@"btn_yes_43") forState:UIControlStateNormal];
    [self.view addSubview:_confirmButton];
    
    _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 20 - 110, _confirmButton.frame.origin.y, 110, 35)];
    [_cancelButton setBackgroundImage:[UIImage imageNamed:@"com_btn_041_n"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [_cancelButton setTitle:_L(@"btn_no_01") forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor colorWithRed:82/255.0 green:96/255.0 blue:34/255.0 alpha:1] forState:UIControlStateNormal];
    [self.view addSubview:_cancelButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 按钮事件

- (void)radioButtonEvent:(UIButton *)sender
{
    //先让_contextViewText失去焦点
    [_contentTextView resignFirstResponder];
    
    int buttonSequnce = sender.tag - 100;
    
    //将当前按钮的状态，一定为真，其他按钮状态一定为假
    for (int i = 0; i < _radioButtons.count; i++) {
        
        BOOL currentState = i == buttonSequnce ? true : false;
        [_radioButtonsState replaceObjectAtIndex:i withObject:@(currentState)];
        
        if ([_radioButtonsState[i] boolValue]) {
            [_radioButtons[i] setImage:[UIImage imageNamed:@"com_icon_021@2x"] forState:UIControlStateNormal];
        }
        else {
            [_radioButtons[i] setImage:[UIImage imageNamed:@"com_icon_020@2x"] forState:UIControlStateNormal];
        }
    }
    
    //根据按钮，切换contentTextView的holder。buttonSequnce + 1（即按钮的个数）=按钮总数时，即为最后一个按钮（“其他”），与其余的按钮使用不同的holder
    _contentTextViewHolder = buttonSequnce + 1 == _radioButtons.count ? _L(@"holder_49") : _L(@"holder_48");
    
    if ([_contentTextView.text isEqualToString:_L(@"holder_48")] || [_contentTextView.text isEqualToString:_L(@"holder_49")]) {
        
        _contentTextView.text = _contentTextViewHolder;
    }
}


///////////////////////////////////
#pragma mark - 确认按钮事件 及 处理逻辑

- (void)confirmButtonEvent
{
    //如果是选择的最后一个项目“其他”，那么_contentTextView.text为空或为holder，就提示用户必须填内容，然后返回
    if ([_radioButtonsState[_radioButtonsState.count - 1] boolValue]   //最后一个按钮的状态如果为真，即被选中
        && (_contentTextView.text.length == 0 || [_contentTextView.text isEqualToString:_contentTextViewHolder])) {
        
        [Helper showAllTextDialog:_L(@"alert_130") inSeconds:2];
        return;
    }
    
    
    JSONRequest* request = [[JSONRequest alloc] init];
    request.URLString = _category == ReportingCategoryPeople ? _JSON_URL_REPORT_USER_ADD : _JSON_URL_REPORT_DYNAMIC_ADD;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    request.successSelector = @selector(reportRequestSuccessSelector:);
    request.delegate = (id)self;
    [request setValue:@(_xID) forParameter:(_category == ReportingCategoryPeople ? @"userId" : @"dynamicId")];
    
    for (NSNumber* number in _radioButtonsState) {
        
        if ([number boolValue]) {
            
            UIButton* button = _radioButtons[[number intValue]];
            [request setValue:button.titleLabel.text forParameter:@"category"];
            
            break;
        }
    }
    
    //holder不传入
    if (![_contentTextView.text isEqualToString:_contentTextViewHolder]) {

        [request setValue:_contentTextView.text forParameter:@"reason"];
    }
    
    [request asynchronous];
}

- (void)reportRequestSuccessSelector:(NSDictionary *)dict
{

    if ([dict[@"status"] intValue] == 1) {

        [self cancelButtonEvent];
        
    }
    
    [Helper showAllTextDialog:dict[@"message"] inSeconds:2];
}

///////////////////////////////////

- (void)cancelButtonEvent
{
    [_contentTextView resignFirstResponder];
    
    if (_delegate && [_delegate respondsToSelector:@selector(reportingViewControllerDidFinish)]) {
        
        [_delegate performSelector:@selector(reportingViewControllerDidFinish)];
    }
}

#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        return NO;
    }
    
    if (textView.text.length > 50) {
        
        textView.text = [textView.text substringToIndex:50];
        return NO;
    }
    
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
    //如果没有任何文字，就放入holder
    if (textView.text.length == 0) {
        
        textView.text = _contentTextViewHolder;
    }

    [UIView animateWithDuration:0.2 animations:^{
        
        self.view.frame = CGRectOffset(self.view.frame, 0, 100);
        
    }];
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    //如果是holder就清空
    if ([_contentTextViewHolder isEqualToString:textView.text]) {
        
        textView.text = @"";
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.view.frame = CGRectOffset(self.view.frame, 0, -100);
        
    }];
}


#pragma mark - JSONRequestDelegate

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:_L(@"title_networkunavailabe") andMessage:nil];
}

@end